package com.xinqi.modules.stats.score.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.core.enums.CourseContentTypeEnum;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.course.clazz.client.ClassClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassResultDTO;
import com.xinqi.modules.stats.score.convert.CourseTotalScoreContentConvert;
import com.xinqi.modules.stats.score.convert.CourseTotalScoreContentSonConvert;
import com.xinqi.modules.stats.score.convert.CourseTotalScoreConvert;
import com.xinqi.modules.stats.score.domain.CourseTotalScoreBaseEntity;
import com.xinqi.modules.stats.score.domain.CourseTotalScoreContentEntity;
import com.xinqi.modules.stats.score.domain.CourseTotalScoreContentSonEntity;
import com.xinqi.modules.stats.score.domain.CourseTotalScoreEntity;
import com.xinqi.modules.stats.score.dto.req.*;
import com.xinqi.modules.stats.score.dto.rsp.CourseTotalScoreContentResultDTO;
import com.xinqi.modules.stats.score.dto.rsp.CourseTotalScoreResultDTO;
import com.xinqi.modules.stats.score.mapper.CourseTotalScoreBaseMapper;
import com.xinqi.modules.stats.score.mapper.CourseTotalScoreContentMapper;
import com.xinqi.modules.stats.score.mapper.CourseTotalScoreMapper;
import com.xinqi.modules.stats.score.service.CourseTotalScoreContentService;
import com.xinqi.modules.stats.score.service.CourseTotalScoreContentSonService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 总成绩课程成绩项目配置表服务层实现
 *
 * @author: system
 * @date: 2023/03/26
 */
@Service("courseTotalScoreContentService")
@RequiredArgsConstructor
public class CourseTotalScoreContentServiceImpl extends BaseServiceImpl<CourseTotalScoreContentMapper, CourseTotalScoreContentEntity> implements CourseTotalScoreContentService {

    private final CourseTotalScoreContentConvert courseTotalScoreContentConvert;

    private final CourseTotalScoreContentSonConvert courseTotalScoreContentSonConvert;

    private final CourseTotalScoreBaseMapper courseTotalScoreBaseMapper;

    private final CourseTotalScoreContentSonService courseTotalScoreContentSonService;

    private final CourseTotalScoreConvert courseTotalScoreConvert;

    private final CourseTotalScoreMapper courseTotalScoreMapper;

    private final ClassClient classClient;

    /*总成绩 编辑*/
    @Override
    public boolean setTotalScoreContent(CourseTotalScoreContentSetDTO dto) {
        List<CourseTotalScoreContentEntity> entityList = dto.getList().stream().map(item -> {
            CourseTotalScoreContentEntity contentEntity = courseTotalScoreContentConvert.update(item);
            contentEntity.setClassId(dto.getClassId());
            contentEntity.setWeight(new BigDecimal(0));
            return contentEntity;
        }).collect(Collectors.toList());
        return this.updateBatchById(entityList);
    }

    /*查询总成绩 成绩项列表*/
    @Override
    public List<CourseTotalScoreContentResultDTO> findTotalScoreContent(CourseTotalScoreClassDTO dto) {
        LambdaQueryWrapper<CourseTotalScoreContentEntity> wrapper = Queries.lambda();
        wrapper.eq(CourseTotalScoreContentEntity::getClassId, dto.getClassId());
        List<CourseTotalScoreContentResultDTO> list = this.baseMapper.selectDtoList(wrapper, courseTotalScoreContentConvert::convert);
        ClassResultDTO classResultDTO = classClient.findClass(dto.getClassId()).getData();
        /*未选择成绩项初始化成绩项(未选中)*/
        if (list == null || list.size() == 0) {
            LambdaQueryWrapper<CourseTotalScoreBaseEntity> wrapperBase = Queries.lambda();
            List<CourseTotalScoreBaseEntity> entities = courseTotalScoreBaseMapper.selectList(wrapperBase);
            List<CourseTotalScoreContentEntity> entityList = entities.stream().map(item -> {
                CourseTotalScoreContentEntity contentEntity = courseTotalScoreContentConvert.convert(item);
                contentEntity.setId(null);
                contentEntity.setCourseId(classResultDTO.getCourseId());
                contentEntity.setClassId(dto.getClassId());
                contentEntity.setWeight(new BigDecimal(0));
                contentEntity.setStatus(0);
                return contentEntity;
            }).collect(Collectors.toList());
            this.saveBatch(entityList);
            list = this.baseMapper.selectDtoList(wrapper, courseTotalScoreContentConvert::convert);
        }
        return list;
    }

    /*查询总成绩 设置的成绩项列表*/
    @Override
    public List<CourseTotalScoreContentResultDTO> findOpenTotalScoreContentContainSon(CourseTotalScoreClassDTO dto) {
        LambdaQueryWrapper<CourseTotalScoreContentEntity> wrapper = Queries.lambda();
        wrapper.eq(CourseTotalScoreContentEntity::getClassId, dto.getClassId());
        wrapper.eq(CourseTotalScoreContentEntity::getStatus, 1);
        wrapper.orderByAsc(CourseTotalScoreContentEntity::getSort);
        List<CourseTotalScoreContentResultDTO> list = this.baseMapper.selectDtoList(wrapper, courseTotalScoreContentConvert::convert);
        // 查询子成绩项
        list.forEach(item -> {
            CourseTotalScoreContentSonClassDTO sonClassDTO = new CourseTotalScoreContentSonClassDTO();
            sonClassDTO.setClassId(item.getClassId());
            sonClassDTO.setType(item.getType());
            if (!item.getType().equals(CourseContentTypeEnum.COURSE_ATTENDANCE.getCode())) {
                item.setList(courseTotalScoreContentSonService.findExistTotalScoreContentSon(sonClassDTO));
            }
        });
        return list;
    }

    /*总成绩完成设置*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean complete(CourseTotalScoreContentCompleteDTO dto) {
        LambdaQueryWrapper<CourseTotalScoreEntity> wrapper = Queries.lambda();
        wrapper.eq(CourseTotalScoreEntity::getClassId, dto.getClassId());
        CourseTotalScoreResultDTO totalScore = courseTotalScoreMapper.selectDtoOne(wrapper, courseTotalScoreConvert::convert);
        if (totalScore == null) {
            CourseTotalScoreEntity totalScoreEntity = new CourseTotalScoreEntity();
            totalScoreEntity.setClassId(dto.getClassId());
            totalScoreEntity.setFullScore(dto.getFullScore());
            courseTotalScoreMapper.insert(totalScoreEntity);
        } else {
            CourseTotalScoreEntity totalScoreEntity = new CourseTotalScoreEntity();
            totalScoreEntity.setId(totalScore.getId());
            totalScoreEntity.setFullScore(dto.getFullScore());
            courseTotalScoreMapper.updateById(totalScoreEntity);
        }

        dto.getList().forEach(item -> {
            CourseTotalScoreContentEntity entity = courseTotalScoreContentConvert.update(item);
            entity.setFullScore(entity.getWeight().multiply(dto.getFullScore()).divide(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_DOWN));
            this.baseMapper.updateById(entity);
            if (item.getList().size() > 0) {
                if (item.getList() != null) {
                    List<CourseTotalScoreContentSonEntity> sonEntities = item.getList().stream().map(v -> {
                        CourseTotalScoreContentSonEntity sonEntity = courseTotalScoreContentSonConvert.update(v);
                        return sonEntity;
                    }).collect(Collectors.toList());
                    courseTotalScoreContentSonService.updateBatchById(sonEntities);
                }
            }
        });
        return true;
    }

}
